<template>
  <!-- 工艺参数监控规则表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="106"
        v-show="!props.isReadonly"
      >
        <!-- <h4 class="mb-[20px] mt-[0px]">基本数据</h4> -->
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="工段"
                prop="workshopSectionId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.workshopSectionId"
                  v-if="!props.isReadonly"
                  placeholder="请选择工段"
                  clearable
                  filterable
                  disabled
                  style="width: 90%"
                >
                  <el-option
                    v-for="item in workshopSectionList"
                    :key="item.id"
                    :label="`${item.workshopSectionCode}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ formData.workshopSectionId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="第一责任人"
                prop="responsiblePersonId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.responsiblePersonId"
                  v-if="!props.isReadonly"
                  placeholder="请选择第一责任人"
                  clearable
                  style="width: 90%"
                  :disabled="!formData.workshopSectionId"
                  @change="changeResponsible"
                >
                  <el-option
                    v-for="item in userList"
                    :label="`${item.userName}`"
                    :value="`${item.userId}`"
                    :key="item.userId"
                  />
                </el-select>
                <span v-else>{{ formData.responsiblePersonName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { validateNumber, validateNumberCanNot1 } from "@/utils/commonHooks";
import { getMdmProcessEquipApi } from "@/utils/commonData";
import SearchFormGroup from "@/views/eam/qr/common/SearchFormGroupQR.vue";
import useEvent from "@/utils/useEvent";
import _ from "lodash-es";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "PCMPSMPARAMMONITORRULERESPONSIBLEPERSON",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const { eventBusEmit } = useEvent();

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  ids: [],
  workshopSectionId: "",
  responsiblePersonId: "",
  responsiblePersonName: "",
});

/** rules规则 */
const rules = reactive({
  responsiblePersonId: [
    { required: true, message: "请选择第一负责人", trigger: "change" },
  ],
});

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.ids = newVal.ids;
    formData.workshopSectionId = newVal.workshopSectionId;
    if (newVal?.workshopSectionId) {
      getUserList(newVal.workshopSectionId);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.ids = [];
  formData.workshopSectionId = "";
  formData.responsiblePersonId = "";
  formData.responsiblePersonName = "";
}

const loading = ref(false);

/** 工艺参数监控规则保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;

      await request({
        url: "/dmpDosPcm/psmparammonitorrule/batchSetResponsiblePerson",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`修改成功`);
      closeDialog();
      emit("reset-table");
    }
  });
}

// 获取工段
const workshopSectionList = ref([]);
const getWorkshopSectionList = async () => {
  await request({
    url: `mdm/mdmworkshopsection/getList`,
    method: "post",
    data: {},
  }).then((res) => {
    workshopSectionList.value = res.data;
  });
};
// 负责人
const userList = ref([]);
const getUserList = async (workshopSectionId?: any) => {
  await request({
    url: "/dmpDosPcm/psmprocessdutyuser/getDetailsByWorkshopSectionId",
    method: "post",
    data: {
      workshopSectionId: workshopSectionId || "",
      userType: 3,
    },
  }).then((res) => {
    userList.value = res.data;
  });
};

const changeResponsible = () => {
  const find = userList.value.find((item) => item.userId === formData.responsiblePersonId);
  formData.responsiblePersonName = find?.userName;
}

onMounted(() => {
  // 负责人
  getUserList();
  getWorkshopSectionList();
});
</script>

